package com.woke.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.bean.HuiKaAreaCode;
import com.bean.HuiKaAreaCodeResponse;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.woke.adapter.HuiKaAreaViewProvider;
import com.woke.adapter.OnItemClickListener;
import com.woke.method.NetworkUtils;
import com.zhongcai.online.R;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by Administrator on 2017/5/10 0010.
 * 广州汇卡 省市
 */

public class HuiKaProvincesAndCitiesDialogFragment extends AppCompatDialogFragment implements DialogInterface.OnKeyListener {

    private OnItemClickListener mItemClickListener;
    private MultiTypeAdapter mPMulitypeAdapter, mCityMulitypeAdapter;
    private Items mProvinceItems = new Items();
    private Items mCityItems = new Items();
    private XRecyclerView mProvinceRecyclerView;
    private XRecyclerView mCityRecyclerView;
    private ViewSwitcher mViewSwitcher;
    private int pageInde = 0;
    private HuiKaAreaCode mProvinceAreaCode, mCityAreaCode;

    public HuiKaAreaCode getProvinceAreaCode() {
        return mProvinceAreaCode;
    }

    public HuiKaAreaCode getCityAreaCode() {
        return mCityAreaCode;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme);
    }


    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);

        Context context = dialog.getContext();
        View rootView = LayoutInflater.from(context).inflate(R.layout.fragment_dialog_provinces_and_cities_2, null);
        mProvinceRecyclerView = (XRecyclerView) rootView.findViewById(R.id.province_recyclerView);
        mCityRecyclerView = (XRecyclerView) rootView.findViewById(R.id.city_recyclerView);
        mViewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher);
        Toolbar mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pageInde >= 1) {
                    mViewSwitcher.showPrevious();
                    pageInde--;
                } else {
                    dismiss();
                }
            }
        });
        initProvince();
        initCity();
        dialog.setContentView(rootView);
        getProvincesData();

        dialog.setOnKeyListener(this);
    }

    private void getProvincesData() {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getHuiKaProvinceAreaCode(mAreaCodeObserver);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
            dismiss();
        }
    }

    private int cityPageIndex = 1;
    private String p_code = "";

    private void getCitiesData(String areaCode, int page) {
        if (NetworkUtils.isConnected(getContext())) {
            p_code = areaCode;
            HttpMethods.getInstance().getHuiKaCityAreaCode(mAreaCodeObserver, areaCode, page);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
        }
    }

    private void initCity() {
        mCityRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCityMulitypeAdapter = new MultiTypeAdapter();
        mCityMulitypeAdapter.register(HuiKaAreaCode.class, new HuiKaAreaViewProvider(listener));
        mCityRecyclerView.setAdapter(mCityMulitypeAdapter);

        mCityMulitypeAdapter.setItems(mCityItems);
        mCityMulitypeAdapter.notifyDataSetChanged();

        mCityRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (getContext() != null && NetworkUtils.isConnected(getContext())) {
                    cityPageIndex = 1;
                    getCitiesData(p_code, cityPageIndex);
                }
                mCityRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                if (getContext() != null && NetworkUtils.isConnected(getContext())) {
                    cityPageIndex++;
                    getCitiesData(p_code, cityPageIndex);
                }
                mCityRecyclerView.loadMoreComplete();
            }
        });
    }

    private void initProvince() {
        mProvinceRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mPMulitypeAdapter = new MultiTypeAdapter();
        mPMulitypeAdapter.register(HuiKaAreaCode.class, new HuiKaAreaViewProvider(listener));
        mProvinceRecyclerView.setAdapter(mPMulitypeAdapter);

        mPMulitypeAdapter.setItems(mProvinceItems);
        mPMulitypeAdapter.notifyDataSetChanged();

        mProvinceRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (getContext() != null && NetworkUtils.isConnected(getContext())) {
                    getProvincesData();
                }
                mProvinceRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                mProvinceRecyclerView.loadMoreComplete();
            }
        });
    }


    private Observer<HuiKaAreaCodeResponse> mAreaCodeObserver = new Observer<HuiKaAreaCodeResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(HuiKaAreaCodeResponse value) {
            if (value != null) {
                List<HuiKaAreaCode> list = value.getBanklist();

                if (list != null && list.size() > 0) {
                    if (list.get(0).isProvinceCode()) {
                        //省 列表
                        pageInde = 0;
                        mProvinceItems.clear();
                        mProvinceItems.addAll(list);
                        if (mPMulitypeAdapter != null) {
                            mPMulitypeAdapter.notifyDataSetChanged();
                        }
                    } else {
                        //市 列表
                        int temp = value.getCurrent_page();
                        if (temp == 1) {
                            mCityItems.clear();
                        }
                        cityPageIndex = temp;
                        mCityItems.addAll(list);
                        if (mCityMulitypeAdapter != null) {
                            mCityMulitypeAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private Toast mToast;

    private void showToast(String msg) {
        if (getContext() == null) return;
        if (mToast == null) {
            mToast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }

    private OnItemClickListener listener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, position);
            }
        }

        @Override
        public void OnItemClick(View view, Object object, int position) {

            if (object instanceof HuiKaAreaCode) {
                HuiKaAreaCode areaCode = (HuiKaAreaCode) object;
                if (areaCode.isProvinceCode()) {
                    mProvinceAreaCode = areaCode;
                    if (NetworkUtils.isConnected(getContext())) {
                        pageInde = 1;
                        mViewSwitcher.showNext();
                        cityPageIndex = 1;
                        getCitiesData(areaCode.getCode(), cityPageIndex);
                    }
                } else {
                    mCityAreaCode = areaCode;
                    dismiss();
                }
            }
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, object, position);
            }
        }
    };

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            if (pageInde >= 1) {
                mViewSwitcher.showPrevious();
                pageInde--;
                return true;
            } else {
                dismiss();
                return false;
            }
        }
        return false;
    }
}
